package com.hu.biz.util.socket;


import com.hu.common.util.adm.Assert;
import io.netty.channel.Channel;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.util.concurrent.GlobalEventExecutor;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName WebSocketChannelManager
 * @Description websocket客户端channel管理器
 * @author 355760
 **/
public class WebSocketChannelManager {

    private static final Map<String, Channel> UID_CHANNEL_MAP = new HashMap<>();
    private static final ChannelGroup CHANNELS = new DefaultChannelGroup(GlobalEventExecutor.INSTANCE);

    public static void addChannel(String uid, Channel channel) {
        UID_CHANNEL_MAP.put(uid, channel);
    }

    public static void removeChannelByUid(String uid) {
        UID_CHANNEL_MAP.remove(uid);
    }

    public static Channel getChannel(String uid) {
        return UID_CHANNEL_MAP.get(uid);
    }

    public static void addChannelGroup(Channel channel) {
        CHANNELS.add(channel);
    }

    public static ChannelGroup getChannelGroup() {
       return CHANNELS;
    }

    public static void removeChannelGroup(Channel channel) {
        CHANNELS.remove(channel);
    }

    /**
     * 从uid-channel映射关系中删除数据
     * @param channel channel
     */
    public static void removeChannelByChannel(Channel channel) {
        if (Assert.notEmpty(UID_CHANNEL_MAP)) {
            for (Map.Entry<String, Channel> entry : UID_CHANNEL_MAP.entrySet()) {
                Channel uChannel = entry.getValue();
                if (uChannel.remoteAddress().equals(channel.remoteAddress())) {
                    UID_CHANNEL_MAP.remove(entry.getKey());
                    break;
                }
            }
        }
    }
}
